package cn.edu.xmu.rocketmqdemo.dao;

import cn.edu.xmu.rocketmqdemo.mapper.OrdersMapper;
import cn.edu.xmu.rocketmqdemo.model.Order;
import cn.edu.xmu.rocketmqdemo.model.OrderItem;
import cn.edu.xmu.rocketmqdemo.model.OrderItemPo;
import cn.edu.xmu.rocketmqdemo.model.OrderPo;
import cn.edu.xmu.rocketmqdemo.util.ResponseCode;
import cn.edu.xmu.rocketmqdemo.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class OrdersDao {
    @Autowired
    private OrdersMapper ordersMapper;

    public ReturnObject<Object> createNewOrder(Order order) {
        System.out.println("现在dao层插入order");
        int flag = ordersMapper.insertNewOrder(order.getOrderPo());
        System.out.println("插入完毕");
        if (flag == 0)
            return new ReturnObject<>(ResponseCode.FIELD_NOTVALID, "失败");

        List<OrderItem> orderItemList = order.getOrderItemList();
        if (orderItemList != null)
            for (OrderItem orderItem : orderItemList) {
                flag = ordersMapper.insertNewOrderItem(orderItem.getOrderItemPo());
                if (flag == 0)
                    return new ReturnObject<>(ResponseCode.FIELD_NOTVALID, "失败");
            }

        return new ReturnObject<>(ResponseCode.OK);

    }










    public ReturnObject<Order> findOrderById(Integer id) {

        // 获取不包含OrderItems的OrderPo，并交由Order代理
        OrderPo orderPo = ordersMapper.selectOrderById(id);
        Order returnOrder = new Order(orderPo);

        List<OrderItem> orderItemList = null;
        if (orderPo != null) {
            // 根据OrderId查找OrderItemPo，并交由OrderItem代理
            List<OrderItemPo> orderItemPoList = ordersMapper.selectOrderItemsByOrderId(orderPo.getId());
            orderItemList = new ArrayList<>(orderItemPoList.size());
            for (OrderItemPo orderItemPo : orderItemPoList)
                orderItemList.add(new OrderItem(orderItemPo));
        }
        // 组装
        returnOrder.setOrderItemList(orderItemList);

        return new ReturnObject<Order>(returnOrder);
    }
}
